using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DropMoneyOnDestroy:MonoBehaviour {

	[SerializeField] float rewardFactor = 0;

	static EventSubscriber<DeathEventArgs> mobDeathEventSubscriber;
	static DropMoneyOnDestroy() {
		mobDeathEventSubscriber=new EventSubscriber<DeathEventArgs>();
		Mob.Death+=mobDeathEventSubscriber.TargetEventHandler;
	}

	Mob mob;

	private void Start() {
		mob=GetComponent<Mob>();
		mobDeathEventSubscriber.SubscribeSingle(mob,MobDeathEventHandler);
	}

	private void OnDestroy() {
		if(mob==null) return;
		mobDeathEventSubscriber.UnsubscribeSingle(mob,MobDeathEventHandler);
	}

	void MobDeathEventHandler(object sender,DeathEventArgs e) {
		float dropValue = mob._maxHP*(1+rewardFactor);
		float growthAmount = 1;
		if(GetComponent<NpcAdditional>()) {
			growthAmount=GetComponent<NpcAdditional>().growthAmount;
		}

		float expectedMoney = dropValue*0.04f/growthAmount;
		float expectedCidium = dropValue*0.01f;

		if(expectedMoney<10) {
			if(Utility.Chance(expectedMoney/10)) expectedMoney=10;
			else expectedMoney=0;
		}
		if(expectedCidium<10) {
			if(Utility.Chance(expectedCidium/10)) expectedCidium=10;
			else expectedCidium=0;
		}

		if(expectedMoney>0) Coin.Create(
			mob.position,Mathf.RoundToInt(Random.Range(expectedMoney*0.85f,expectedMoney*1.15f))
		);
		if(expectedCidium>0) EnergyPickup.Create(
			mob.position,Mathf.RoundToInt(Random.Range(expectedCidium*0.85f,expectedCidium*1.15f))
		);

		if(Utility.Chance((dropValue+(dropValue>200 ? 100 : 0))/2000)) HealthPickup.Create(mob.position);

	}
}
